const {
  getPermission_id,
  getRolesList,
  addRoleService,
  deleteRoleById,
  editRoleService,
  getPowers,
  getAllPowersService,
  getAllPowersListService,
  updatepermissionService,
} = require("../service/roles.service");

class RoleController {
  // 更新用户-permission
  async updatepermission(ctx, next) {
    // console.log(ctx.request.body);
    const res = await updatepermissionService(ctx.request.body);
    if (res.length >= 1)
      return (ctx.body = {
        meta: {
          status: 200,
        },
        msg: "修改permission成功",
      });
    else {
      ctx.body = {
        meta: {
          status: 504,
        },
        msg: "修改permission失败",
      };
    }
  }

  // 获取roles在添加用户时候用
  async getRolelist(ctx, body) {
    const res = await getRolesList();
    console.log(res);
    ctx.body = res;
  }

  // 获取roles
  async getRole(ctx, next) {
    // 获取用户id
    const id = ctx.request.params.id;
    // 获取permission_id列表
    const permissionList = await getPermission_id(id);
    ctx.body = {
      data: permissionList,
      meta: {
        msg: "获取角色信息成功",
        status: 200,
      },
    };
  }

  async getRoles(ctx, next) {
    //   获取角色列表+角色对应的权限
    const data = await getRolesList();

    // 每个角色追加 权限
    for (let i = 0; i < data.length; i++) {
      if (data[i].permission_id) {
        const res = await getPowers(data[i].permission_id);
        const ress = res.filter(function (item) {
          return item.length >= 1;
        });
        console.log(ress);
        data[i].power = ress;
        console.log("-------------------------------");
      }
    }
    ctx.body = data;
  }

  // 获取全部权限
  async getAllPowers(ctx, next) {
    const res = await getAllPowersService();
    ctx.body = res[0];
  }

  // 获取全部3级权限
  async getAllPowersList(ctx, next) {
    const res = await getAllPowersListService();
    ctx.body = res[0];
  }

  // 添加角色
  async addRole(ctx, next) {
    const roleinfo = ctx.request.body;
    // 往数据库中插入信息
    const data = await addRoleService(roleinfo);
    if (data.length >= 1)
      return (ctx.body = {
        data,
        meta: {
          status: 200,
        },
      });
    else {
      return (ctx.body = "添加角色失败");
    }
  }

  // 删除角色
  async deleteRole(ctx, next) {
    const { id } = ctx.request.params;
    const result = await deleteRoleById(id);
    if (result.length >= 1)
      return (ctx.body = {
        msg: "删除角色成功",
        status: 200,
      });
    else return ctx.app.emit("error", new Error("删除角色失败"), ctx);
  }

  // 编辑角色
  async editRole(ctx, next) {
    const roleinfo = ctx.request.body;
    const { id } = ctx.request.params;
    const result = await editRoleService(id, roleinfo);
    if (result.length >= 1)
      return (ctx.body = {
        msg: "修改成功",
        status: 200,
      });
  }
}

module.exports = new RoleController();
